<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="!orderInfo.no || orderData.status == 'SCRAP'"
          @click="handleAdd"
          v-hasPermi="['basic:bomDetail:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single || orderData.status == 'SCRAP'"
          @click="handleUpdate"
          v-hasPermi="['basic:bomDetail:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple || orderData.status == 'SCRAP'"
          @click="handleDelete"
          v-hasPermi="['basic:bomDetail:remove']"
        >删除</el-button>
      </el-col>

    </el-row>

    <el-table  height="25vh"  v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <af-table-column label="物料编码" align="center" prop="productNo" />
      <af-table-column label="物料名称" align="center" prop="productName" />
      <af-table-column label="物料类型" align="center" prop="productType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.basic_product_type" :value="scope.row.productType"/>
        </template>
      </af-table-column>
      <af-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="单位" align="center" prop="productUnit" />
    </el-table>


    <!-- 添加或修改单据明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="物料" prop="productNo">
          <el-select @change="changeProduct" style="width:100%;" v-model="form.productNo" filterable placeholder="请选择物料">
            <el-option
              v-for="dict in productList"
              :key="dict.productNo"
              :label="dict.productName + '（' + dict.productNo + '）'"
              :value="dict.productNo"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model.trim="form.quantity"  placeholder="请输入数量" />
        </el-form-item>

        <el-form-item label="单位" prop="productUnit">
          <el-input v-model.trim="form.productUnit" placeholder="请输入单位" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBomItemDetail, getBomItemDetail, delBomItemDetail, addBomItemDetail, updateBomItemDetail } from "./api/bomDetail";
import { listProduct } from "@/api/basic/product";

export default {
  name: "salesOrderDetail",
  dicts: ['basic_product_type'],
  props:{
    orderData:{}
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 已选择的物料
      notInProductNos: [],
      productNos: [],
      pitchOnTotalOrderQty: 0,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单据明细表格数据
      detailList: [],
      // 物料列表
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 9999,
        no: null,
        batchNo: null,
        productNo: null,
        storehouseLocationNo: null,
        picker: null,
        orderDetailStatus: null,
        createUser: null,
        updateUser: null,
        sort: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productNo: [
          { required: true, message: "物料不能为空", trigger: "change" }
        ],
        quantity: [
          { required: true, message: "数量不能为空", trigger: "blur" },
        ]
      },
      // 订单信息
      orderInfo:{
        no : null
      }
    };
  },
  created() {
    this.getList();
  },
  watch: {
    // 监视订单信息变动
    orderData(newValue){
      if(!newValue || !newValue.no){
        this.orderInfo = {no : null};
      }else {
        this.orderInfo = newValue;
      }
      this.getList();
    }
  },
  methods: {
    /** 获取物料列表 */
    getListProduct(){
      listProduct({pageNum:1,
        pageSize:99999,
        notInProductNos:this.notInProductNos
      }).then(response => {
        this.productList = response.rows;
      });
    },
    // 修改物料
    changeProduct(){
      const product = this.productList.find(item => item.productNo === this.form.productNo)
      this.$set(this.form,'productType',product.productType);
      this.$set(this.form,'productName',product.productName);
    },
    /** 查询单据明细列表 */
    getList() {
      this.loading = true;

      this.queryParams.bomNo = this.orderInfo.no;
      if(!this.queryParams.bomNo){
        this.detailList = [];
        this.total = 0;
        this.loading = false;
        return;
      }

      listBomItemDetail(this.queryParams).then(response => {
        this.detailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$set(this,'queryParams',{});
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.productNos = selection.map(item => item.productNo)
      this.pitchOnTotalOrderQty = 0;
      selection.forEach(item => this.pitchOnTotalOrderQty = this.pitchOnTotalOrderQty + item.orderQty);
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.bomNo = this.orderInfo.no;
      this.open = true;
      // 过滤BOM主表的物料以及明细已有的物料
      this.$set(this,'notInProductNos',[]);
      this.notInProductNos.push(this.orderData.productNo);
      this.detailList.forEach((row) => {
        this.notInProductNos.push(row.productNo);
      });
      // 重新获取物料列表
      this.getListProduct();
      this.title = "添加BOM组件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // 过滤BOM主表的物料以及明细已有的物料
      this.$set(this,'notInProductNos',[]);
      this.notInProductNos.push(this.orderData.productNo);
      this.detailList.forEach((row) => {
        if (row.productNo != this.productNos[0]) {
          this.notInProductNos.push(row.productNo);
        }
      });

      // 重新获取物料列表
      this.getListProduct();
      const id = row.id || this.ids
      getBomItemDetail(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改BOM组件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (parseInt(this.form.quantity) < 1) {
            this.$modal.msgWarning("数量请输入正整数");
            return;
          }
          if (this.form.id != null) {
            updateBomItemDetail(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBomItemDetail(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(this.$t('deleteTip', { num: ids.length })).then(function() {
        return delBomItemDetail(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('invoice/salesOrderDetail/export', {
        ...this.queryParams, ids: this.ids
      }, `单据明细管理_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
